#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import _mysql, _mysql_exceptions
from hbaseservice import HBaseService
import formatMysqlRow


def insertinto(dbh, tablename, field, value,dryrun=False):
    if len(field) != len(value):
        print 'the len of field is not equal len of value:'
        print '*' * 60
        print field
        print value
        print '*' * 60
        return False
    q = "INSERT INTO %s (%s) VALUES (%s);" % (tablename, ','.join(field), ','.join(map(lambda x: "'" + str(x) + "'", value)))
    if dryrun:
        print q
        return True
    try:
        dbh.query(q)
    except _mysql_exceptions.IntegrityError, e:
        with open('errorlog.txt','a') as errorfile:
            errorfile.write(str(e)+'\n'+','.join(value)+'\n')
        print str(e).decode('UTF-8')
        return False
    return True

def loadSummaryToMysql(day,tablename='post_summary_new'):
    hbase_service = HBaseService()
    rowkey='A_%s' % day
    rs = hbase_service.queryByRowKey('FourthInfo', rowkey)
    if (not rs) or (rs.get('cf:InfoCount') is None):
        return
    fields = ['stat_date', 'infos', 'users']
    values = [day,rs.get('cf:InfoCount'),rs.get('cf:UserCount')]
    connect=formatMysqlRow.connect_to_base_dicts('dbwww58com_58_stats')
    insertinto(connect, tablename, fields, values)
    connect.close()
    hbase_service.shutdown

if __name__ == '__main__':
    if len(sys.argv) !=2:
        print 'usage: %s Date!' % (sys.argv[0])
        sys.exit(1)
    day=sys.argv[1]
    loadSummaryToMysql(day)
    sys.exit(0)